const router = require('koa-router')()
var svgCaptcha = require('svg-captcha');
const jwt=require("jsonwebtoken")
const mykey="djxdjxdjx"
const formidable = require("formidable")
const path = require('path')
const fs = require('fs')
const dirPath = path.join(path.resolve(__dirname, '../'), '/public/images')

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})
router.post("/captcha", async (ctx, next) => {
  var captcha = svgCaptcha.create();
  ctx.session.captcha = captcha.text;
  ctx.body = captcha.data;
})

router.post("/login", async (ctx, next) => {
  console.log(ctx.request.body);
  console.log(ctx.session);
  let body = JSON.parse(ctx.request.body);
  let username = body.username;
  let pwd = body.password;
  if (username == "zhangsan" && pwd == "1234") {
    let token = jwt.sign({ username: "zhangsan" }, mykey)
    ctx.body = { token: token };
  }
})

// 图片上传
const uploadImg = (ctx) => {
  const form = formidable({
      multiples: true,
      uploadDir: dirPath,
      keepExtensions: true,
      allowEmptyFiles: false
  });

  return new Promise((resolve, reject) => {
      form.parse(ctx.req, (err, fields, files) => {
          //ctx.req原生的node的http请求模块；ctx.require.body是经过koa二次封装之后的
          if (err) {
              reject(err);
              return;
          }
          let keys = Object.keys(files);//获取files对象中的属性名[formData传入的图片]
          keys?.map((key) => {
              console.log(key);
              // 将文件重命名为原本的文件名
              // fs.rename(path.join(dirPath, `/${files[key].newFilename}`), path.join(dirPath, `/${files[key].originalFilename}`),
              // (err) => {
              // if (err) {
              // console.log(err);
              // } else {
              // console.log('file is reset!');
              // }
              // })
          })
          resolve({ ok: true, fields, files });
      });
  });
}

router.get('/upload', async (ctx, next) => {
  let token = ctx.req.headers.authorization;
  let result = jwt.verify(token, mykey);
  console.log(result);
  ctx.body = await uploadImg(ctx);
})

router.get('/getpage', async (ctx, next) => {
   let page = fs.readdirSync(dirPath);
   ctx.body = page;
})

router.post('/verify', async (ctx, next) => {
  let body = JSON.parse(ctx.request.body);
  let name = body.name;
  let id = body.id;
  if (name && id) {
    let token = jwt.sign({ name: name }, mykey);
    ctx.body = { token: token }
  }
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
